package pixelwaks.ctrl.impl;

import java.awt.Point;

import pixelwaks.core.impl.Explosion;
import pixelwaks.core.impl.Game;

import common.ctrl.IObserver;
import common.gui.IViewable;

public class ExplosionCtrl implements IObserver, Runnable {
	
	private long animationDelay = 100;	
	private int iteration;	
	private Thread thread;
	private IViewable iv;
	private Explosion explosion;
			
	public void startAnimation(Explosion exp, Point p) {
		
		try {
			Game.lock.acquire();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		explosion = exp;
		
		explosion.setPosition(p);
		explosion.setActive(true);
		explosion.setCurrentImage(0);
		
		iteration = 0;
		
		thread = new Thread(this);
	    thread.setName("Explosion");
	    thread.start();
	}
	
	private synchronized void update() {
		
		if(iteration < explosion.getAnimationSize()) {
			explosion.setCurrentImage(iteration);
//			CURRENT_IMAGE = iteration;
			iteration++;			
		} else {
			explosion.setActive(false);
//			done = true;
		}
		
		iv.updateView(null);
	}

	@Override
	public void run() {
		
		long time = System.currentTimeMillis();
		
		while (explosion.isActive()) {
			
			try {				
				update();
				time += animationDelay ;
				Thread.sleep(Math.max(0,time - System.currentTimeMillis()));
			}catch (InterruptedException e) {
				System.out.println(e);
			}
		}
		Game.lock.release();
		Game.getInstance().getMode().nextPlayer();
	}

	@Override
	public void addView(IViewable iv) {
		
		this.iv = iv;
	}
}